package com.xm.queue;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * 阻塞队列
 *   特点：线程安全，支持阻塞等待（当队列满/空时阻塞操作）。
 *   适用场景：生产者-消费者模型。
 *   实现：双锁，动态扩展队列，putLock与takeLock读写锁分离
 *   原因：链表需动态分配节点，双锁减少内存分配阻塞
 */
public class TestLinkedBlockingQueue05 {
    public static void main(String[] args) {
        BlockingQueue<String> blockingQueue = new LinkedBlockingQueue<String>(2);

        //生产者线程
        new Thread(() ->{
            try {
                blockingQueue.put("Task1");
                blockingQueue.put("Task2");
                blockingQueue.put("Task3");
//                blockingQueue.put("Task4");
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }).start();

        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        //已加入队列任务，Task1、Task2
        for (String task : blockingQueue) {
            System.out.println(task);
        }
        //消费者线程
        new Thread(() ->{
            try {
                Thread.sleep(1000);
                String task = blockingQueue.take();
                System.out.println("处理任务：" + task);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }).start();

        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        System.out.println(blockingQueue.poll());//Task2
        System.out.println(blockingQueue.poll());//Task3
        System.out.println(blockingQueue.poll());//null
    }
}
